package com.shengyijie.activity.tab;
  
import java.util.ArrayList;

import org.apache.http.HttpResponse;

import com.shengyijie.activity.R;      
import com.shengyijie.activity.commen.ItemActivity;  
import com.shengyijie.adapter.view.AlertBox; 
import com.shengyijie.adapter.view.HomeGalleryFlow;
import com.shengyijie.adapter.view.AlertBox.OnCanceledListener; 
import com.shengyijie.adapter.viewadapter.HomeGalleryAdapter;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.database.dataoperate.AdvertPicDB;
import com.shengyijie.model.http.HttpConnectApi;
import com.shengyijie.model.json.JsonParser;
import com.shengyijie.model.object.Listobject.AdvertPicList; 
import com.shengyijie.model.object.baseobject.AdvertPic;  

import android.app.Activity; 
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;   
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class HomeActivity extends Activity implements OnClickListener{
   
	private HomeGalleryFlow galleryFlow;
	private AlertBox mypDialog;
	public Task task;  
	private HttpConnectApi httpConnect;
	private TextView title;
	 
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
         setContentView(R.layout.home);
         initView();
         getAdver();
         //setImageAdapter();
    }
    
    public void initView(){  
		galleryFlow = (HomeGalleryFlow) findViewById(R.id.gallery); 
		galleryFlow.setOnItemClickListener(itemClickListener);
		galleryFlow.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				AdvertPic content=(AdvertPic)parent.getItemAtPosition(position%adapter.size);
	    		// ContextApplication.itemName=content.g;
				title.setText(content.getPro_name());
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}});
		
//		MotionEvent e1 = MotionEvent.obtain(
//			    SystemClock.uptimeMillis(), 
//			    SystemClock.uptimeMillis(),  
//			    MotionEvent.ACTION_DOWN, 89.333336f, 265.33334f, 0);
//			MotionEvent e2 = MotionEvent.obtain(
//			    SystemClock.uptimeMillis(), 
//			    SystemClock.uptimeMillis(), 
//			    MotionEvent.ACTION_UP, 300.0f, 238.00003f, 0);
//
//			galleryFlow.onFling(e1, e2, -800, 0);
		
		title = (TextView) findViewById(R.id.name); 
    } 
    public OnItemClickListener  itemClickListener = new OnItemClickListener() { 
		public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
			try{  
				current_id=position%adapter.size;
				 AdvertPic content=(AdvertPic)parent.getItemAtPosition(position%adapter.size);
	    		 // ContextApplication.itemName=content.g;
				 title.setText(content.getPro_name());
	    		 pro_id=Integer.parseInt(content.getPro_id());
		    	 task=new Task();  
  		         task.execute(TASK_LOAD_ITEM); 
  		         isScroll=false;
			}catch(Exception e){}
		}
  };
    
    public void getAdver(){
    	galleryFlow.postDelayed(new Runnable() {  
	             public void run() {  
	            	 mypDialog=new AlertBox(HomeActivity.this,HomeActivity.this,findViewById(R.id.home)); 
	            	 mypDialog.setCompletedListener(new OnCanceledListener(){ 
	 					@Override
	 					public void onCanceled() { 
	 						if(task.getStatus()==AsyncTask.Status.RUNNING){
	 				    		 task.cancel(true); 
	 				    		isScroll=true;
	 						  }
	 					}});
	            	 task=new Task();  
	        	     task.execute(TASK_LOAD_ADVER); 
	             }  
	         },1);
	  }
    
    
    public ArrayList<AdvertPic> contentList=new ArrayList<AdvertPic>();
    HomeGalleryAdapter adapter;
    public void setImageAdapter(){
		 try{ 
			 
			AdvertPicDB dh=new AdvertPicDB(this, "Yuele", 1);
			dh.openWrite(); 
			if(!dh.isTableExits(AdvertPicDB.TABLE_ADVERT)){
		       dh.createTable();	
			}
			dh.deleteAllRecords();
			
			   
			for (int i = 0; i < advertPicList.getCount(); i++) {  
				AdvertPic advertPic=new AdvertPic();
				advertPic.setId(advertPicList.getItem(i).getId());
				advertPic.setPro_id(advertPicList.getItem(i).getPro_id());
				advertPic.setPic_url(advertPicList.getItem(i).getPic_url());
				advertPic.setCreate(advertPicList.getItem(i).getCreate());
				advertPic.setPro_name(advertPicList.getItem(i).getPro_name());
				contentList.add(advertPic);
				long state=dh.insertItem(advertPicList.getItem(i));
				long s=state+=1;
			} 
			dh.close();
			 adapter = new HomeGalleryAdapter(this,this, contentList,galleryFlow); 
		 }catch(Exception e){}
	 }
    
    public int getImageAdapterFromLocal(){
		 try{  
			AdvertPicDB dh=new AdvertPicDB(this, "Yuele", 1);
			dh.openWrite(); 
			if(!dh.isTableExits(AdvertPicDB.TABLE_ADVERT)){
		       dh.createTable();	
			}
			Cursor cursor=dh.fetchAllRecords(); 
			advertPicList=new AdvertPicList();
			advertPicList=advertPicList.getAdvertPicListFromCursor(cursor); 
			cursor.close();
			dh.close(); 
			for (int i = 0; i < advertPicList.getCount(); i++) {  
				AdvertPic advertPic=new AdvertPic();
				advertPic.setId(advertPicList.getItem(i).getId());
				advertPic.setPro_id(advertPicList.getItem(i).getPro_id());
				advertPic.setPic_url(advertPicList.getItem(i).getPic_url());
				advertPic.setCreate(advertPicList.getItem(i).getCreate());
				advertPic.setPro_name(advertPicList.getItem(i).getPro_name());
				contentList.add(advertPic); 
			}  
			adapter = new HomeGalleryAdapter(this,this, contentList,galleryFlow); 
			if(advertPicList.getCount()>0&&adapter!=null)
				return 1;
		 }catch(Exception e){}
		 return 0;
	 }

	@Override
	public void onClick(View v) { 
		switch(v.getId()){
		   case R.id.sina:
			   
			  break;
		}
	}
	public boolean onKeyDown(int keyCode,KeyEvent event) {   
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
	    	
				 new AlertDialog.Builder(this).setTitle("提示")
				 .setMessage("确定退出？")
				 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) { 
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				  })
				  .setNegativeButton("取消", new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int whichButton) {
					     }
				  })
				  .show();
	    	
	         return true;   
	     } else
	         return super.onKeyDown(keyCode,event);   
	 }
	
	  AdvertPicList advertPicList=new AdvertPicList();
	  AdvertPic advertPic;
	  public String doGetRecommendedList(){
	     	String result="re_fail";
	        httpConnect=HttpConnectApi.getInstance();
	        try { 
	            HttpResponse response=httpConnect.getOneAdver(1);
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    advertPicList=jsonParser.getAdert(response);
	           	     
	           	    	if(advertPicList.getCount()>0){ 
	           	    		setImageAdapter();
	           	    	    result="re_ok";
	           	    	}else{
	           	    		int state=getImageAdapterFromLocal();
	           	    		if(state==1)
	           	    			result="re_ok";
	           	    	}
	           	    	   
//	           	    	else if(projectList.getCount()==0)
//	           	    		result="re_0";
	           	     
				}else{
					int state=getImageAdapterFromLocal();
       	    		if(state==1)
       	    			result="re_ok";
				}
	            return result;
	        }catch (Exception e) {
	        	int state=getImageAdapterFromLocal();
   	    		if(state==1)
   	    			result="re_ok";
	        } 
			return result;
	   }
	
	int pro_id; 
	int current_id=0;
	boolean isCan=false;
	public String doGetProjectDetail(){
     	String result="pr_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getProjectDetail(pro_id);
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    ContextApplication.project=jsonParser.getProgectDetail(response);
           	    if(ContextApplication.project!=null){ 
           	    	 result="pr_ok"; 
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
 }
	 public void changeToItemActivity(){
		 Intent intent=new Intent();
		 intent.setClass(this, ItemActivity.class);
		 this.startActivityForResult(intent,1);
	 }
	 
	 @Override 
	    protected void onStart() {  
	        super.onStart(); 
	        isScroll=true;
	    } 
	   public void onRestart(){ 
		 super.onRestart(); 
		 isScroll=true;
		 }  
	    @Override 
	    protected void onResume() {  
	        super.onResume(); 
	        isScroll=true;
	        if(isCan)
	           scroll();
	         
	    } 
	    @Override 
	    protected void onPause() {  
	        super.onPause(); 
	        isScroll=false;
	    } 
	    @Override 
	    protected void onStop() {  
	        super.onStop(); 
	        isScroll=false;
	    } 
	    @Override 
	    protected void onDestroy() {  
	        super.onDestroy(); 
	        isScroll=false;
	    } 
	boolean isScroll=true;
	 public void scroll(){
		 new Thread(new Runnable() {  
	            @Override  
	            public void run() {  
	                // TODO Auto-generated method stub  
	                while (isScroll) {   
	                    try {  
	                    	//current_id = current_id % adapter.size;   
		                	Message msg = Message.obtain();
		    				msg.what = SCROLL;
		    				handler.sendMessage(msg);
	                        Thread.sleep(2000);  
	                        current_id++;  //放置在Thread.sleep(2000)  
	                    } catch (Exception e) {   
	                        e.printStackTrace();  
	                    }   
	                }  
	            }  
	        }).start();  
	 }
	 
	 private final static int SCROLL=21; 
	
	 private final static int ALERT_LOADING=1; 
	 private final static int RESULT_LOAD_ITEMDETAIL_OK=16;
	 private final static int RESULT_LOAD_ITEMDETAIL_FAIL=17; 
	 
	 private final static int RESULT_LOAD_ITEMLIST_OK=2;
	 private final static int RESULT_LOAD_ITEMLIST_0=3; 
	 private final static int RESULT_LOAD_ITEMLIST_FAIL=4;
	  
	 private final static String TASK_LOAD_ITEM="loaditem";   
	 private final static String TASK_LOAD_ADVER="loadadver";  
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
			 	   case SCROLL:  
//			 		  galleryFlow.setAnimation(AnimationUtils.loadAnimation(HomeActivity.this, android.R.anim.decelerate_interpolator));
//			 		 galleryFlow.setAnimationDuration(1000);
			 		  galleryFlow.setSelection(current_id,true);
			 		// galleryFlow.set
				       break; 
				   case ALERT_LOADING: 
					    mypDialog.show();
					    break; 
				   case RESULT_LOAD_ITEMLIST_FAIL:
					   try{
					      mypDialog.dismiss();
					     // scroll();
					      //isCan=true;
					     // isScroll=true;
					     // scroll();
					      Toast.makeText(HomeActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					      galleryFlow.setAdapter(null); 
					    }catch(Exception e){}
					     break;
				    case RESULT_LOAD_ITEMLIST_0:
					     mypDialog.dismiss(); 
					     //isScroll=true;
					    // scroll();
					     Toast.makeText(HomeActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					     break;  
                   case RESULT_LOAD_ITEMLIST_OK:
                   	try{
                    	 mypDialog.dismiss(); 
                    	 title.setText(advertPicList.getItem(0).getPro_name());
                    	 galleryFlow.setAdapter(adapter);
                    	 scroll();
                    	 isCan=true;
                   	 }catch(Exception e){}
					     break; 
                   case RESULT_LOAD_ITEMDETAIL_OK:
                 	     mypDialog.dismiss(); 
                 	     changeToItemActivity();
					     break; 
                  case RESULT_LOAD_ITEMDETAIL_FAIL:
					     mypDialog.dismiss(); 
					     isScroll=true;
					     Toast.makeText(HomeActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					     break; 
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			if(params[0].equals(TASK_LOAD_ITEM)){
				return doGetProjectDetail();
			}else if(params[0].equals(TASK_LOAD_ADVER)){
				return doGetRecommendedList();
			}else
				return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result);

			if(result.equals("pr_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("pr_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_OK;
				handler.sendMessage(msg);
			} else if(result.equals("re_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("re_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_OK;
				handler.sendMessage(msg);
			}else if(result.equals("re_0")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_0;
				handler.sendMessage(msg);
			}  
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute(); 
		    Message msg = Message.obtain();
		    msg.what = ALERT_LOADING;
			handler.sendMessage(msg); 
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
    
    
}